<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body></body>
  <script>
    let data = {
      name: "张三",
      age: 20,
    };
    function setData(key, val) {
      // 真正修改数据
      data[key] = val;
      // 干其他事
      console.log("修改了", key, "的值为：", val); //对应框架更新视图的操作
    }

    setData("name", "李四");

    let data2 = new Proxy(
      { name: "张三", age: 50 },
      {
        // 修改对象属性时 执行的方法
        set(target, key, val) {
          target[key] = val;
          // 插入其他操作
          console.log("修改了", key, "的值为：", val);
          return true;
        },
        get(target, key) {
          return target[key];
        },
      }
    );

    data2.name = "李四"; //触发set
    console.log(data2.name); //触发get
  </script>
</html>
